package com.shuziren.controller.interciew_transcripts;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shuziren.abnormal.CustomException;
import com.shuziren.core.vo.Result;
import com.shuziren.domain.CandidateEntity;
import com.shuziren.pojo.dto.InterviewScheduleDto;
import com.shuziren.pojo.entity.InterviewSchedule;
import com.shuziren.pojo.entity.vo.InterviewScheduleVo;
import com.shuziren.pojo.vo.InterviewScheduleVVo;
import com.shuziren.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/interviewSchedule")
public class InterviewScheduleController {

    @Autowired
    private InterviewScheduleService interviewScheduleService;

    @Autowired
    private  CandidateService candidateService;

    @Autowired
    private InterPersonService interPersonService;

    @Autowired
    private InterviewPositionService interviewPositionService;


    /**
     * 添加面试安排
     *
     * @param interviewSchedule 待添加的面试安排对象，通过请求体传递
     * @return 添加结果，true表示成功，false表示失败
     */
    @PostMapping("/save")
    public Result save(@Validated @RequestBody InterviewSchedule interviewSchedule) throws CustomException {
        if (interviewSchedule == null) {
            throw new CustomException("面试安排对象为空");
        }
        if (candidateService.getById(interviewSchedule.getCandidateId()) == null){
            throw new CustomException("该候选人不存在");
        }
        if (interviewPositionService.getById(interviewSchedule.getPositionId()) == null){
            throw new CustomException("该职位不存在");
        }
        if (interPersonService.getById(interviewSchedule.getDigitalInterviewerId()) == null){
            throw new CustomException("该数字面试官不存在");
        }
        interviewSchedule.setCreatedAt(new Date());
        //生成一个随机的8位密码
        String password = RandomUtil.randomString(8);
        interviewSchedule.setTemporaryPasswords(password);
        boolean b = interviewScheduleService.addInterviewSchedule(interviewSchedule);
        if (b) {
            return Result.success("添加成功");
        }
        //设置定时任务，根据添加的面试时间触发
//        AiTaskService aiTaskService = new AiTaskService();
//        aiTaskService.scheduleInterviewTask(interviewSchedule.getInterviewTime());
        return Result.fail("添加失败");
    }


    /**
     * 取消面试删除面试安排
     *
     * @param id 待删除的面试安排的ID，通过URL路径传递
     * @return 删除结果，true表示成功，false表示失败
     */
    @GetMapping("/delete")
    public Result delete(Integer id) throws CustomException {
        if (id == null) {
            throw new CustomException("面试安排ID为空");
        }
        if (interviewScheduleService.getById(id) == null){
            throw new CustomException("该面试安排不存在");
        }
        boolean result = interviewScheduleService.removeById(id);
        return Result.success(result);
    }

    /**
     * 更新面试安排信息
     *
     * @param interviewSchedule 待更新的面试安排对象，通过请求体传递
     * @return 更新结果，true表示成功，false表示失败
     */
    @PostMapping("/update")
    public Result update(@Validated @RequestBody InterviewSchedule interviewSchedule) throws CustomException {
        interviewSchedule.setUpdatedAt(new Date());
        return Result.success(interviewScheduleService.updateInterviewSchedule(interviewSchedule));
    }

    /**
     * 根据ID获取面试安排详情
     *
     * @param id 待查询的面试安排的ID，通过URL路径传递
     * @return 面试安排对象，如果找不到则返回null
     */
    @GetMapping("/getById")
    public Result getById(Integer id) throws CustomException {
        if (id == null) {
            throw new CustomException("面试安排ID为空");
        }
        // 调用服务层方法获取面试安排对象
        InterviewScheduleVo interviewSchedule1 = interviewScheduleService.getInterviewScheduleById(id);

        // 检查返回对象是否为null
        if (interviewSchedule1 == null) {
            throw new CustomException("未找到ID为 " + id + " 的面试安排");
        }
        InterviewScheduleVo interviewSchedule = interviewScheduleService.getInterviewScheduleById(id);
        return Result.success(interviewSchedule);
    }

    /**
     * 获取所有面试安排列表
     *
     * @return 面试安排列表，可能为空
     */
    @PostMapping("/list")
    public Result list(@Validated @RequestBody InterviewScheduleDto interviewSchedule) throws CustomException {
        if (interviewSchedule == null) {
            throw new CustomException("查询条件对象为空");
        }

        if (interviewSchedule.getCandidateId() != null && interviewSchedule.getCandidateId() != 0) {
            // 获取所有候选人ID列表（包含有效性校验）
            List<Integer> candidateIds = candidateService.list().stream()
                    .map(CandidateEntity::getId)
                    .collect(Collectors.toList());
            
            if (!candidateIds.contains(interviewSchedule.getCandidateId())) {
                throw new CustomException("候选人不存在");
            }
        }

        Page<InterviewScheduleVVo> allInterviewSchedulePage = interviewScheduleService.getAllInterviewSchedulePage(interviewSchedule);
        if (allInterviewSchedulePage == null || allInterviewSchedulePage.getRecords().isEmpty()) {
            // 如果分页结果为null或者没有记录，返回失败结果
            return Result.success("没有相关用户数据");
        }
        return Result.success(allInterviewSchedulePage);
    }

}
